package com.zeroxml.cms.web.action.admin;

import com.zeroxml.cms.web.action.BaseAdminAction;
import com.zeroxml.cms.service.ILinkService;
import com.zeroxml.cms.service.ICatalogService;
import com.zeroxml.cms.bo.Link;
import com.zeroxml.cms.bo.Catalog;
import com.wyvoid.core.persistent.hibernate.HibernatePage;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.integration.spring.SpringBean;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * User: cjp
 * Date: 2007-9-22
 * Time: 13:55:42
 */
@UrlBinding("/admin/linkManage.do")
public class LinkManageAction extends BaseAdminAction {
    @SpringBean
    private ILinkService linkService;
    @SpringBean
    private ICatalogService catalogService;
    private HibernatePage<Link> links;
    private Link link;
    private int curPage;
    private long linkId;
    private List<Catalog> catalogs;

    public void setLinkService(ILinkService linkService) {
        this.linkService = linkService;
    }

    public void setCatalogService(ICatalogService catalogService) {
        this.catalogService = catalogService;
    }

    public HibernatePage<Link> getLinks() {
        return links;
    }

    public void setCurPage(int curPage) {
        this.curPage = curPage;
    }

    public Link getLink() {
        return link;
    }

    public void setLink(Link link) {
        this.link = link;
    }

    public void setLinkId(long linkId) {
        this.linkId = linkId;
    }

    public List<Catalog> getCatalogs() {
        return catalogs;
    }

    @DefaultHandler
    public Resolution linkManage() {
        int pageSize = 10;
        links = linkService.getAllLinks(curPage, pageSize);
        return getAdminResolution("links");
    }

    public Resolution editForm() {
        if (linkId > 0) {
            link = linkService.getLink(linkId);
        }
        return getAdminResolution("editLinkForm");
    }

    public Resolution editLink() {
        if (link.getId() > 0) {
            Link tempLink = linkService.getLink(link.getId());
            try {
                BeanUtils.copyProperties(tempLink, link);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            linkService.updateLink(tempLink);
        } else {
            linkService.addLink(link);
        }
        return new RedirectResolution(getClass());
    }

    public Resolution deleteLink(){
        linkService.deleteLink(linkId);
        return new RedirectResolution(getClass());
    }
    @After
    public void init() {
        catalogs = catalogService.getCatalogList(0);
    }
}
